#pragma once

#include <unistd.h>
#include <string>
#include <spdlog/spdlog.h>

#include "exports.h"
#include "rc.h"
#include "sview.h"

namespace DB_NAME {

constexpr const size_t kWritableBufferSize = 64 * KB;

class WritableFile {
 public:
  explicit WritableFile(int fd) : pos_(0), fd_(fd) {}
  ~WritableFile() {
    if (fd_ >= 0) {
      Close();
    }
  }

  RC Append(const SView &data_view, bool sync = false);
  RC Close();
  RC Flush() { return flush_buffer(); }
  RC Sync();
 private:
  RC sync_fd();
  RC write_unbuffered(const char* data, size_t size);
  RC flush_buffer();
  INTERNAL_BUF_COPY
 private:
  char buf_[kWritableBufferSize];
  size_t pos_;
  int fd_;
};

}